package com.bosssoft.trainee.mbg.util.handler;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: wuxin
 * @Date: 2022/6/17
 * @Project rbac
 * @Version 1.0
 * @Description
 */
@Slf4j
@Component
public class ListOfIntegerHandler implements TypeHandler<List<Integer>> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<Integer> integers, JdbcType jdbcType) throws SQLException {
        log.info("Change List<Integer> to String...");
        StringBuilder sb = new StringBuilder();
        for (Integer s : integers) {
            sb.append(s).append(",");
        }
        preparedStatement.setString(i, sb.substring(0, sb.toString().length() - 1));
    }

    @Override
    public List<Integer> getResult(ResultSet resultSet, String s) throws SQLException {
        log.info("Change String to List<Integer> 1 ...");
        String str = resultSet.getString(s);
        if (StringUtils.hasLength(str)) {
            String[] strings = str.split(",");
            return Arrays.stream(strings).map(Integer::valueOf).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<Integer> getResult(ResultSet resultSet, int i) throws SQLException {
        log.info("Change String to List<Integer> 2 ...");
        String str = resultSet.getString(i);
        if (StringUtils.hasLength(str)) {
            String[] strings = str.split(",");
            return Arrays.stream(strings).map(Integer::valueOf).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<Integer> getResult(CallableStatement callableStatement, int i) throws SQLException {
        log.info("Change String to List<Integer> 3 ...");
        String str = callableStatement.getString(i);
        if (StringUtils.hasLength(str)) {
            String[] strings = str.split(",");
            return Arrays.stream(strings).map(Integer::valueOf).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }
}